﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MachineQA.Model;

namespace MachineQA
{
    /// <summary>
    /// Interaction logic for LocationTab.xaml
    /// </summary>
    public partial class LocationTab : UserControl
    {
        public LocationTab()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            LocationsListbox.DataContext = Constants.entities.Locations.Select((i) => i.Name).ToList();
        }

        private void NewLocationNameBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TryEnableSave();
        }

        private void TryEnableSave()
        {
            LocationSaveButton.IsEnabled = !Constants.entities.Locations.Select((i) => i.Name).Contains(NewLocationNameBox.Text);
        }

        private void LocationSaveButton_Click(object sender, RoutedEventArgs e)
        {
            Location newLocation = new Location();
            newLocation.Name = NewLocationNameBox.Text;
            Constants.entities.AddToLocations(newLocation);
            try
            {
                Constants.entities.SaveChanges();
                LocationSaveButton.IsEnabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was a problem loading the new location. Error: \n" + ex.Message);
            }

            // Not perfect but works for now (Probably fine until 10's of items since the listbox is 
            // cleared and reloaded reasonably quick for a small number of elements. 
            // Need to have IObservable wrapper around entity context query ... how?
            LocationsListbox.DataContext = null;
            LocationsListbox.DataContext = Constants.entities.Locations.Select((i) => i.Name).ToList();
        }
    }
}
